'use strict';

const Service = require('egg').Service;

class MenuService extends Service {
  async add(data) {
    const { ctx } = this;
    const { menuType } = data;
    let icon = '';
    if (menuType === '1') {
      icon = 'folder';
    } else if (menuType === '2') {
      icon = 'file';
    } else if (menuType === '3') {
      icon = 'button';
    }
    try {
      const res = await ctx.model.Menu.create({
        ...data,
        icon,
        createdTime: Date.now(),
      });
      return this.ctx.helper.success({ id: res.id }, '新增成功');
    } catch (e) {
      return this.ctx.helper.fail(e.name);
    }
  }

  async find(id) {
    const { ctx } = this;
    try {
      const res = await ctx.model.User.findAll({
        attributes: [ 'id', 'username', 'realName' ],
        where: { id, logicDelete: 0 },
      });
      return this.ctx.helper.success(res[0], '更新成功');
    } catch (e) {
      return this.ctx.helper.fail(e.name);
    }
  }

  async update(data) {
    const { id } = data;
    const { ctx } = this;
    try {
      const res = await ctx.model.Menu.update(
        { ...data, updatedTime: Date.now() },
        { where: { id } }
      );
      return this.ctx.helper.success(res[0]);
    } catch (e) {
      return this.ctx.helper.fail(e.name);
    }
  }

  async delete(id) {
    const { ctx } = this;
    try {
      const res = await ctx.model.Menu.update(
        { logicDelete: 1 },
        { where: { id } }
      );
      return this.ctx.helper.success(res[0], '删除成功');
    } catch (e) {
      return this.ctx.helper.fail(e.name);
    }
  }

  async list() {
    const { ctx } = this;
    try {
      const res = await ctx.model.Menu.findAll({
        where: { logicDelete: 0 },
        order: [[ 'id', 'ASC' ]],
        raw: true,
      });
      const tree = ctx.helper.arrayToTree(res, 0);
      return this.ctx.helper.success({
        count: tree.length,
        rows: tree,
      });
    } catch (e) {
      return ctx.helper.fail(e);
    }
  }
}

module.exports = MenuService;
